import React, { useEffect, useState } from "react";
import { Button, Checkbox, Form, Input, Select, Space } from "antd";
import { OptionType, QuestionCheckboxPropsType } from "./interface";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import cloneDeep from "lodash.clonedeep";

const PropComponent: React.FC<QuestionCheckboxPropsType> = (
  props: QuestionCheckboxPropsType
) => {
  const {
    title,
    list = [],
    prompt,
    isVertical,
    isRequired,
    isRandom,
    onChange,
    disabled,
  } = props;
  const [form] = Form.useForm();
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    form.setFieldsValue({
      title,
      list,
      prompt,
      isVertical,
      isRequired,
      isRandom,
    });
  }, [title, list, prompt, isVertical, isRequired, isRandom]);

  function handleValueChange() {
    const newProps = form.getFieldsValue();
    if (onChange) onChange(newProps);
  }

  function handleBlur(index: number) {
    if (index === -1) {
      const currentValue = form.getFieldValue("title");

      if (currentValue !== "") return;
      form.setFieldValue("title", inputValue);
      if (onChange) onChange(form.getFieldsValue());
      form.resetFields();
    } else {
      const currentItem = list[index];

      if (currentItem.label !== "") return;
      const newList = cloneDeep(list);
      newList[index].label = inputValue;
      form.setFieldValue("list", newList);
      if (onChange) onChange(form.getFieldsValue());
    }
  }

  return (
    <Form
      layout="vertical"
      initialValues={{ title, list, prompt, isVertical, isRequired, isRandom }}
      form={form}
      onValuesChange={handleValueChange}
      disabled={disabled}
    >
      <Form.Item
        label="标题"
        name="title"
        rules={[{ required: true, message: "请输入标题" }]}
      >
        <Input
          onFocus={(e) => setInputValue(e.target.value)}
          onBlur={() => handleBlur(-1)}
          allowClear
        />
      </Form.Item>
      <Form.Item label="选项（勾选前面的复选框为默认选中该选项）">
        <Form.List name="list">
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ key, name }, index) => (
                <Space key={key} align="baseline">
                  <Form.Item name={[name, "checked"]} valuePropName="checked">
                    <Checkbox />
                  </Form.Item>
                  <Form.Item
                    name={[name, "label"]}
                    rules={[
                      { required: true, message: "请输入选项内容" },
                      {
                        validator(_, label) {
                          const { list } = form.getFieldsValue();
                          let num = 0;
                          list.forEach((opt: OptionType) => {
                            if (opt.label === label) num++;
                          });
                          if (num > 1)
                            return Promise.reject(
                              new Error("选项内容不能重复")
                            );
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <Input
                      onFocus={(e) => setInputValue(e.target.value)}
                      onBlur={() => handleBlur(index)}
                      allowClear
                    />
                  </Form.Item>
                  {index > 0 && (
                    <MinusCircleOutlined onClick={() => remove(index)} />
                  )}
                </Space>
              ))}
              <Form.Item style={{ marginBottom: "0" }}>
                <Button
                  block
                  type="link"
                  icon={<PlusOutlined />}
                  onClick={() =>
                    add({
                      label: `默认选项${list.length + 1}`,
                      value: `item${list.length + 1}`,
                      checked: false,
                    })
                  }
                >
                  添加选项
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </Form.Item>
      <Form.Item label="提示答案" name="prompt">
        <Select mode="multiple" options={list} allowClear />
      </Form.Item>
      <Form.Item name="isVertical" valuePropName="checked">
        <Checkbox>竖向排列</Checkbox>
      </Form.Item>
      <Form.Item name="isRequired" valuePropName="checked">
        <Checkbox>是否必填</Checkbox>
      </Form.Item>
      <Form.Item name="isRandom" valuePropName="checked">
        <Checkbox>随机答案（从答卷选项中随机选取一个答案）</Checkbox>
      </Form.Item>
    </Form>
  );
};

export default PropComponent;
